package io.gitee.duxiuhuan.mailbox.database;

import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface QueryTableMapper {

    @Update({
            "<script>",
            "<if test='databaseType == \"mysql\"'>",
            "    CREATE TABLE IF NOT EXISTS ${tableName} (id BIGINT AUTO_INCREMENT PRIMARY KEY, user_id BIGINT NOT NULL, session_id BIGINT NOT NULL, user_or_system INT NOT NULL, model VARCHAR(255), content TEXT, create_time VARCHAR(255));",
            "</if>",
            "<if test='databaseType == \"pgsql\"'>",
            "    CREATE TABLE IF NOT EXISTS ${tableName} (id BIGSERIAL PRIMARY KEY, user_id BIGINT NOT NULL, session_id BIGINT NOT NULL, user_or_system INT NOT NULL, model VARCHAR(255), content TEXT, create_time VARCHAR(255));",
            "</if>",
            "</script>"
    })
    void createTable(@Param("tableName") String tableName, @Param("databaseType") String databaseType);

    @Delete({
            "<script>",
            "<if test='databaseType == \"mysql\"'>",
            "    DROP TABLE IF EXISTS ${tableName};",
            "</if>",
            "<if test='databaseType == \"pgsql\"'>",
            "    DROP TABLE IF EXISTS ${tableName};",
            "</if>",
            "</script>"
    })
    void dropTable(@Param("tableName") String tableName, @Param("databaseType") String databaseType);

    @Update({
            "<script>",
            "<if test='databaseType == \"mysql\"'>",
            "    RENAME TABLE ${oldTableName} TO ${newTableName};",
            "</if>",
            "<if test='databaseType == \"pgsql\"'>",
            "    ALTER TABLE ${oldTableName} RENAME TO ${newTableName};",
            "</if>",
            "</script>"
    })
    void renameTable(@Param("oldTableName") String oldTableName, @Param("newTableName") String newTableName, @Param("databaseType") String databaseType);

    @Select({
            "<script>",
            "<if test='databaseType == \"mysql\"'>",
            "    SELECT table_name FROM information_schema.tables WHERE table_schema = 'public' AND table_name LIKE #{tableName};",
            "</if>",
            "<if test='databaseType == \"pgsql\"'>",
            "    SELECT tablename FROM pg_tables WHERE schemaname = 'public' AND tablename LIKE #{tableName};",
            "</if>",
            "</script>"
    })
    List<String> getTablesByPattern(@Param("tableName") String tableName, @Param("databaseType") String databaseType);
}